package com.zhkj.crawl.rank;

import com.alibaba.fastjson.JSON;
import com.zhkj.crawl.config.StringPool;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

@Slf4j
public class EbayService extends BaseService{

    public static void main(String[] args) {
        String itemId = "284487056627";
        ProductDetail detail = new ProductDetail(itemId);

        getDetail(detail);
        searchByKeyword(detail);

        log.info("查找结束：{}的排名是{}", detail.getItemId(), detail.getRank());
    }

    private static void searchByKeyword(ProductDetail detail) {
        // 一页48条（不是固定的 有时候47条） 取前1000名
        int LIMIT_RANK = 1000,
                EBAY_PS = 48,
                limit = (LIMIT_RANK % EBAY_PS > 0) ? LIMIT_RANK /EBAY_PS + 1 : LIMIT_RANK / EBAY_PS,
                page = 0,
                currentIdx = 0;

        log.info("取前{}名 约在第{}页停止", LIMIT_RANK, limit);
        while (currentIdx < LIMIT_RANK){
            ++page;
            Element element = getPage(detail.getCateUrl(), page, 0);
            if(element == null){
                log.info("第{}页 查找出错 - {}", page, "");
                continue;
            }
            Elements elements = element.select("li.s-item");
            if(elements == null || elements.size() == 0){
                log.info("第{}页 查找出错 - {}", page, elements == null ? "" : 0);
                continue;
            }

            Element find = checkItem(element, detail.getKeyword());
            if(find != null){
                int idx = Integer.parseInt(find.attr("idx"));
                int rank = currentIdx + idx;
                log.info("第{}页第{}条 排名：{} content: {}", page, idx, rank, find.text());
                detail.setRank(String.valueOf(rank));
                break;
            }
            log.info("-----------第{}页{}条中未找到-----------", page, elements.size());
            currentIdx += elements.size();
        }
        detail.setRank(String.format("大于前%s名", currentIdx));
    }

    private static void getDetail(ProductDetail detail){
        String url = String.format("https://www.ebay.com/itm/%s", detail.getItemId());
        Document document = jsoupGet(url, 0);
        String title = document.select(".sw_email").attr("etafsharetitle");
        title = title.replace("  | eBay", StringPool.EMPTY);

        String href = document.select("li.bc-w").last().select("a").attr("href");
        String cateUrl = href.replace("https://www.ebay.com/b/", StringPool.EMPTY);

        detail.setKeyword(title);
        detail.setCateUrl(cateUrl);

        log.info("{} 的详情：{}", detail.getItemId(), JSON.toJSONString(detail));
    }

    private static Element checkItem(Element element, String keyword) {
        Elements items = element.select(".s-item");
        for (int i = 0; i < items.size(); i++) {
            Element child = items.get(i);
            String title = child.select(".s-item__image-img").attr("alt");
            if(keyword.equals(title)){
                child.attr("idx", (i + 1) + "");
                return child;
            }
        }
        return null;
    }

    public static Element getPage(String cateUrl, int page, Integer deep){
        String url = String.format("https://www.ebay.com/b/%s?_pgn=%d", cateUrl, page);

        Document document = jsoupGet(url, deep);
        Elements validEle = document.select(".srp-controls__count-heading");

        if(++deep <= MAX_RETRY && (validEle == null || validEle.size() == 0)){
            System.out.printf("wait and retry %s\n", deep);
//                showIp();
            sleep(1);
            return getPage(cateUrl, page, deep);
        }
        return document.body();
    }

}
